package com.tea.web.controller.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tea.web.controller.conf.WxConfs;
import com.tea.web.controller.model.WxModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @PACKAGE_NAME: com.fruit.web.controller.utils
 * @CLASSNAME: WxLoginUtil
 * @DEACRIPTION:
 * @AUTHOR: GuoChen
 * @DATE: 2023/2/22
 * @WEEK: 周三
 **/
@Slf4j
@Component
public class WxLoginUtil {

    @Autowired
    private WxConfs wxConf;

    /**
     * 获取微信openId等信息
     * @param code 微信code
     * @return
     */
    public WxModel weChatAuthByCode(String code) {
        String loginUrl = wxConf.getLoginUrl()
                .replace("{appid}", wxConf.getAppId())
                .replace("{secret}", wxConf.getSecret())
                .replace("{code}", code);
        String responseStr = HttpUtil.get(loginUrl);
        JSONObject jsonObject = JSONUtil.parseObj(responseStr);
        log.info("响应数据：" + jsonObject);
        String openId = jsonObject.getStr("openid");
        String sessionKey = jsonObject.getStr("session_key");
        WxModel wxModel = new WxModel();
        wxModel.setOpenId(openId);
        wxModel.setSessionKey(sessionKey);
        return wxModel;
    }
}
